package com.sjw.workflow.example;

import com.sjw.workflow.core.WorkflowContext;
import com.sjw.workflow.dag.WorkflowDAG;
import com.sjw.workflow.dag.WorkflowNode;
import com.sjw.workflow.dag.LogicalExpression;
import com.sjw.workflow.agent.DataProcessingAgent;
import com.sjw.workflow.agent.ValidationAgent;
import com.sjw.workflow.agent.ReportGenerationAgent;
import com.sjw.workflow.engine.WorkflowEngine;
import com.sjw.workflow.engine.WorkflowExecutionResult;
// import org.slf4j.Logger;
// import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;

/**
 * 示例Workflow
 * 演示Agent1和Agent2完成后，启动Agent3的DAG执行流程
 */
public class ExampleWorkflow {
    
    // private static final Logger logger = LoggerFactory.getLogger(ExampleWorkflow.class);
    
    public static void main(String[] args) {
        try {
            // 创建示例工作流
            ExampleWorkflow workflow = new ExampleWorkflow();
            
            // 执行工作流
            WorkflowExecutionResult result = workflow.executeExampleWorkflow();
            
            // 输出结果
            printResults(result);
            
        } catch (Exception e) {
            System.err.println("Workflow execution failed: " + e.getMessage());
        }
    }
    
    /**
     * 执行示例工作流
     */
    public WorkflowExecutionResult executeExampleWorkflow() throws Exception {
            System.out.println("Starting example workflow execution");
        
        // 1. 创建工作流DAG
        WorkflowDAG dag = createWorkflowDAG();
        
        // 2. 创建执行上下文
        WorkflowContext context = new WorkflowContext("example-workflow-001");
        
        // 3. 设置初始数据
        setupInitialData(context);
        
        // 4. 创建执行引擎
        WorkflowEngine engine = new WorkflowEngine();
        
        try {
            // 5. 执行工作流
            CompletableFuture<WorkflowExecutionResult> future = engine.execute(dag, context);
            WorkflowExecutionResult result = future.get();
            
            System.out.println("Example workflow execution completed");
            return result;
            
        } finally {
            // 6. 关闭执行引擎
            engine.shutdown();
        }
    }
    
    /**
     * 创建工作流DAG
     */
    private WorkflowDAG createWorkflowDAG() {
        WorkflowDAG dag = new WorkflowDAG("example-workflow");
        
        // 创建Agent
        DataProcessingAgent agent1 = new DataProcessingAgent();
        ValidationAgent agent2 = new ValidationAgent();
        ReportGenerationAgent agent3 = new ReportGenerationAgent();
        
        // 创建节点 - 使用Agent的ID作为节点ID
        WorkflowNode node1 = new WorkflowNode("data-processor", "Data Processing Node", agent1);
        WorkflowNode node2 = new WorkflowNode("validator", "Validation Node", agent2);
        
        // Agent3需要等待Agent1和Agent2都完成
        LogicalExpression condition = LogicalExpression.and(
            LogicalExpression.agentSuccessful("data-processor"),
            LogicalExpression.agentSuccessful("validator")
        );
        WorkflowNode node3 = new WorkflowNode("report-generator", "Report Generation Node", agent3, condition);
        
        // 添加节点到DAG
        dag.addNode(node1);
        dag.addNode(node2);
        dag.addNode(node3);
        
        // 添加依赖关系
        // Agent1和Agent2可以并行执行
        // Agent3依赖Agent1和Agent2的完成
        dag.addEdge("data-processor", "report-generator");
        dag.addEdge("validator", "report-generator");
        
        System.out.println("Created workflow DAG with " + dag.size() + " nodes");
        return dag;
    }
    
    /**
     * 设置初始数据
     */
    private void setupInitialData(WorkflowContext context) {
        // 设置测试数据
        String testData = "This is a sample text for processing and validation. " +
                         "It contains multiple sentences and various words for analysis.";
        
        List<String> testList = Arrays.asList(
            "item1", "item2", "item3", "item4", "item5"
        );
        
        Map<String, Object> testMap = new HashMap<>();
        testMap.put("key1", "value1");
        testMap.put("key2", "value2");
        testMap.put("key3", 123);
        testMap.put("key4", true);
        
        // 将数据存储到上下文中
        context.setGlobalData("testText", testData);
        context.setGlobalData("testList", testList);
        context.setGlobalData("testMap", testMap);
        
        // 为Agent1设置输入数据 - 使用正确的键名
        Map<String, Object> agent1Input = new HashMap<>();
        agent1Input.put("data", testData);
        context.setGlobalData("data-processor_input", agent1Input);
        
        // 为Agent2设置输入数据 - 使用正确的键名
        Map<String, Object> agent2Input = new HashMap<>();
        agent2Input.put("data", testList);
        context.setGlobalData("validator_input", agent2Input);
        
        System.out.println("Initial data setup completed");
    }
    
    /**
     * 打印执行结果
     */
    private static void printResults(WorkflowExecutionResult result) {
        System.out.println("\n" + "=".repeat(80));
        System.out.println("WORKFLOW EXECUTION RESULTS");
        System.out.println("=".repeat(80));
        
        System.out.printf("Workflow ID: %s%n", result.getWorkflowId());
        System.out.printf("Execution Time: %d ms%n", result.getExecutionTime());
        System.out.printf("Total Nodes: %d%n", result.getTotalNodes());
        System.out.printf("Completed Nodes: %d%n", result.getCompletedNodes());
        System.out.printf("Failed Nodes: %d%n", result.getFailedNodes());
        System.out.printf("Success Rate: %.2f%%%n", 
            result.getTotalNodes() > 0 ? (double) result.getCompletedNodes() / result.getTotalNodes() * 100 : 0);
        
        System.out.printf("Overall Status: %s%n", 
            result.isSuccess() ? "SUCCESS" : result.isPartialSuccess() ? "PARTIAL SUCCESS" : "FAILURE");
        
        if (result.getError() != null) {
            System.out.printf("Error: %s%n", result.getError());
        }
        
        // 打印执行日志
        System.out.println("\nExecution Log:");
        System.out.println("-".repeat(40));
        List<String> logs = result.getContext().getExecutionLog();
        for (String log : logs) {
            System.out.println(log);
        }
        
        // 打印Agent结果摘要
        System.out.println("\nAgent Results Summary:");
        System.out.println("-".repeat(40));
        Map<String, com.sjw.workflow.core.AgentResult> agentResults = result.getContext().getAllAgentResults();
        for (Map.Entry<String, com.sjw.workflow.core.AgentResult> entry : agentResults.entrySet()) {
            String agentId = entry.getKey();
            com.sjw.workflow.core.AgentResult agentResult = entry.getValue();
            System.out.printf("Agent %s: %s (execution time: %d ms)%n", 
                agentId, agentResult.getStatus(), agentResult.getExecutionTime());
        }
        
        // 打印最终报告（如果存在）
        if (agentResults.containsKey("report-generator")) {
            com.sjw.workflow.core.AgentResult reportResult = agentResults.get("report-generator");
            if (reportResult.getStatus() == com.sjw.workflow.core.ExecutionStatus.SUCCESS) {
                System.out.println("\nFinal Report Generated Successfully!");
                Map<String, Object> reportOutput = reportResult.getOutput();
                if (reportOutput.containsKey("summary")) {
                    System.out.println("Report Summary: " + reportOutput.get("summary"));
                }
            }
        }
        
        System.out.println("\n" + "=".repeat(80));
    }
}
